package com.duke.shaking.register;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.duke.shaking.BaseActivity;
import com.duke.shaking.R;
import com.duke.shaking.ShakeApplication;
import com.duke.shaking.TitleActivity;
import com.duke.shaking.net.AsyncHttpResponseWithResultHandler;
import com.duke.shaking.net.NetUtils;
import com.duke.shaking.pojo.User;
import com.duke.shaking.profile.InputNicknameActivity;
import com.duke.shaking.utils.AppUtils;

public class Register2Activity extends TitleActivity {
	private User regUser;
	
	public TextView txtTelNo;
	public String secret;
	private Activity activity;
	private AQuery aQuery;
	private BroadcastReceiver smsIntentReceiver;
	
	public Register2Activity() {
		this.activity = this;
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        this.aQuery = new AQuery(this.activity);
        
        
        Intent i = getIntent();
        regUser = (User)i.getSerializableExtra("regUser");
        if (regUser == null || regUser.getSex() == User.sex_unk) {
        	toast(R.string.err_no_sex);
        }
        
        if (regUser == null || regUser.getTelNo() == null) {
        	toast(R.string.err_invalid_telno);
        }
        
        txtTelNo = (TextView)findViewById(R.id.txt_tel_no);
        if (txtTelNo != null && regUser != null) {
        	txtTelNo.setText(regUser.getTelNo());
        }
        
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		IntentFilter intentFilter = new IntentFilter("SmsMessage.intent.MAIN");
		smsIntentReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				String sender = intent.getStringExtra("sms_sender");
				String msg = intent.getStringExtra("sms_msg");
				
				//toast("receive sms, sender:" + sender + "; msg: " + msg);
				populateVerifyCode(sender, msg);
			}
		};
		
		//this.registerReceiver(smsIntentReceiver, intentFilter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		this.unregisterReceiver(smsIntentReceiver);
	}

	public void onRightBtn(View v) {
		if (regUser == null || regUser.getSex() == User.sex_unk) {
        	toast(R.string.err_no_sex);
        	return;
        }
        
        if (regUser == null || regUser.getTelNo() == null) {
        	toast(R.string.err_invalid_telno);
        	return;
        }
        
		EditText txtSecret = (EditText)findViewById(R.id.edit_secret);
		if (txtSecret == null) {
			return;
		}
		secret = txtSecret.getText().toString();
		if (secret == null || secret.equals("")) {
			return;
		}
		
		AsyncHttpResponseWithResultHandler responseHandler = new AsyncHttpResponseWithResultHandler(){
			
        	@Override
			public void onResultSuccess(String response) {
				// TODO Auto-generated method stub
				super.onResultSuccess(response);
				
				/*PrefUtils.getInstance(activity, activity.getString(R.string.registerPref))
					.addString(activity.getString(R.string.verifyCode), secret)
					.commit();*/
				
				JSONObject bodyJson = this.getBody(response);
				if(bodyJson != null) {
					String authToken = bodyJson.optString(NetUtils.TOKEN);
					if(authToken == null) {
						// no auth token , exception with register
						Toast.makeText(activity, R.string.err_register_exception, Toast.LENGTH_LONG).show();
					} else {
						onAfterLogin(authToken, secret);
					}
				}
			}

			@Override
			public void onResultFailure(String result) {
				// TODO Auto-generated method stub
				super.onResultFailure(result);
				
				toast(R.string.err_invalid_verify_code);
			}
        };
        
        Map<String, String> params = new HashMap<String, String>();
        params.put(NetUtils.MOBILE, regUser.getTelNo());
        params.put(NetUtils.SEX, String.valueOf(regUser.getSex()));
        params.put(NetUtils.CODE, secret);
        NetUtils.register(this, responseHandler, params);
		
	}
	
	private void onAfterLogin(String authToken, String secret) {
		regUser.setHasLogin(true);
		regUser.setAuthToken(authToken);
		regUser.setPassword(secret);
		regUser.setJob(User.NO_JOB);
		//i.putExtra("regUser", regUser);
		BaseActivity.setMe(regUser);
		ShakeApplication.getShared().afterLogin(regUser);
		finish();
		go(InputNicknameActivity.class, null, null);
	}
	
	private void populateVerifyCode(String sender, String msg) {
		if(sender == null || msg == null) {
			return;
		}
		String fromAddr = AppUtils.getProperty("smsAddr");
		if(sender.equalsIgnoreCase(fromAddr)) {
			String smsStart = AppUtils.getProperty("smsStart");
			String smsEnd = AppUtils.getProperty("smsEnd");
			int pos = msg.indexOf(smsEnd);
			String code = "";
			if(pos != -1) {
				int pos2 = msg.indexOf(smsStart);
				if(pos2 != -1) {
					code = msg.substring(pos2 + smsStart.length(), pos);
				}
			}
			aQuery.id(R.id.edit_secret).text(code);
			
			toast("已自动获取并输入密码");
		}
	}

	/**
	 * Read the verify code from SMS
	 * @return Return the code if get it or empty string if fail
	 * @deprecated
	 */
	private String readCodeFromSms() {
		final String SMS_URI_INBOX = "content://sms/inbox";
		final String fromAddr = AppUtils.getProperty("smsAddr");
		String[] projection = new String[] { "_id", "address", "body", "date", "type" };
		
		// TODO: add the time to selection sql
		Cursor cursor = this.getContentResolver().query(
				Uri.parse(SMS_URI_INBOX), 
				projection, 
				"address=?", 
				new String[]{fromAddr}, 
				"date desc");
		Log.i("SMS", "cursor =" + cursor);
		if(cursor != null) {
			int count = cursor.getCount();
			if(count > 0) {
				cursor.moveToFirst();

				long id = cursor.getLong(0);
				String address = cursor.getString(1);
				String body = cursor.getString(2);
				long timestamp = cursor.getLong(3);

				Log.i("SMS", "id=" + id + "; address=" + address + "; body=" + body + "; timestamp=" + timestamp);
				
				String smsStart = AppUtils.getProperty("smsStart");
				String smsEnd = AppUtils.getProperty("smsEnd");
				int pos = body.indexOf(smsEnd);
				if(pos != -1) {
					return body.substring(smsStart.length(), pos);
				}
				
			}
		}
		return "";
	}

	@Override
	protected int getLayoutId() {
		return R.layout.activity_register2;
	}

	@Override
	protected void onTitleInit() {
		// TODO Auto-generated method stub
		initTitle(TITLE_BTN_EXIST | TITLE_BTN_BACK,
				R.string.back,
				TITLE_BTN_EXIST,
				R.string.done,
				R.string.title_fill_reg_secret);
	}
}
